
package com.zhj.agent.resolver;

import com.zhj.agent.support.ClassEnhancePluginDefine;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PluginBootstrap {

    /** PLUGINS */
    private static final String PLUGINS = "spring-agent-plugin.def";

    /**
     * 读取 spring-agent-plugin.def 文件，加载出需要的插件
     *
     * @return plugin definition list.
     * @since 1.0.0
     */
    public List<ClassEnhancePluginDefine> loadPlugins() {
        ClassPathResource classPathResource = new ClassPathResource(PLUGINS);
        List<ClassEnhancePluginDefine> enhancePluginDefines = new ArrayList<>();
        try {
            if (!classPathResource.exists()) {
                return enhancePluginDefines;
            }
            InputStreamReader streamReader = new InputStreamReader(classPathResource.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            String tempString;
            while ((tempString = reader.readLine()) != null) {
                if (tempString.trim().length() == 0 || tempString.startsWith("#")) {
                    continue;
                }
                if (StringUtils.isEmpty(tempString)) {
                    continue;
                }

                String[] pluginDefine = tempString.split("=");
                if (pluginDefine.length != 2) {
                    continue;
                }
                log.debug("读取到插件类：{}", pluginDefine[1]);
                ClassEnhancePluginDefine classEnhancePluginDefine = (ClassEnhancePluginDefine) Class.forName(pluginDefine[1],
                                                                                                             true,
                                                                                                             this.getClass().getClassLoader())
                    .newInstance();
                enhancePluginDefines.add(classEnhancePluginDefine);
            }
        } catch (Exception e) {
            log.error("读取插件配置异常：", e);
        }
        return enhancePluginDefines;
    }

}
